#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, site 
import re, urllib
import datetime, time
import shutil

import sqlite3dbm

from generator import *
from paneo import *

import web
from sqlobject import *
sqlhub.processConnection = connectionForURI('sqlite://'+ARTICLES_DB)

#render
from web.contrib.template import render_mako

render = render_mako(   directories=[PANEO_ROOT+'/_cms/templates/'],
                        input_encoding='utf-8',
                        output_encoding='utf-8',
                        default_filters=["none_to_blank", "unicode"],
                        encoding_errors='replace', 
                        imports = RENDER_IMPORTS )

def formtempcopy( key ):
    shutil.copyfile(PANEO_ROOT+'/_paneo_files/html/formmail_hed.html', PANEO_SITE_DATA_DIR+'forms/formmail_%s_hed.html' % key)
    shutil.copyfile(PANEO_ROOT+'/_paneo_files/html/formmail_ftr.html', PANEO_SITE_DATA_DIR+'forms/formmail_%s_ftr.html' % key)
    shutil.copyfile(PANEO_ROOT+'/_paneo_files/html/formmail_ent.html', PANEO_SITE_DATA_DIR+'forms/formmail_%s_ent.html' % key)
    shutil.copyfile(PANEO_ROOT+'/_paneo_files/html/formmail_thx.html', PANEO_SITE_DATA_DIR+'forms/formmail_%s_thx.html' % key)
    shutil.copyfile(PANEO_ROOT+'/_paneo_files/html/formmail_msg.html', PANEO_SITE_DATA_DIR+'forms/formmail_%s_msg.html' % key)
    return

def formtempdel( key ):
    if os.path.exists(PANEO_SITE_DATA_DIR+'forms/formmail_%s_hed.html' % key):
        os.remove(PANEO_SITE_DATA_DIR+'forms/formmail_%s_hed.html' % key)
    if os.path.exists(PANEO_SITE_DATA_DIR+'forms/formmail_%s_ftr.html' % key):
        os.remove(PANEO_SITE_DATA_DIR+'forms/formmail_%s_ftr.html' % key)
    if os.path.exists(PANEO_SITE_DATA_DIR+'forms/formmail_%s_ent.html' % key):
        os.remove(PANEO_SITE_DATA_DIR+'forms/formmail_%s_ent.html' % key)
    if os.path.exists(PANEO_SITE_DATA_DIR+'forms/formmail_%s_thx.html' % key):
        os.remove(PANEO_SITE_DATA_DIR+'forms/formmail_%s_thx.html' % key)
    if os.path.exists(PANEO_SITE_DATA_DIR+'forms/formmail_%s_msg.html' % key):
        os.remove(PANEO_SITE_DATA_DIR+'forms/formmail_%s_msg.html' % key)
    return

def formtempmove( key, key2 ):
    if os.path.exists(PANEO_SITE_DATA_DIR+'forms/formmail_%s_hed.html' % key):
        os.rename(PANEO_SITE_DATA_DIR+'forms/formmail_%s_hed.html' % key,PANEO_SITE_DATA_DIR+'forms/formmail_%s_hed.html' % key2)
    if os.path.exists(PANEO_SITE_DATA_DIR+'forms/formmail_%s_ftr.html' % key):
        os.rename(PANEO_SITE_DATA_DIR+'forms/formmail_%s_ftr.html' % key,PANEO_SITE_DATA_DIR+'forms/formmail_%s_ftr.html' % key2)
    if os.path.exists(PANEO_SITE_DATA_DIR+'forms/formmail_%s_ent.html' % key):
        os.rename(PANEO_SITE_DATA_DIR+'forms/formmail_%s_ent.html' % key,PANEO_SITE_DATA_DIR+'forms/formmail_%s_ent.html' % key2)
    if os.path.exists(PANEO_SITE_DATA_DIR+'forms/formmail_%s_thx.html' % key):
        os.rename(PANEO_SITE_DATA_DIR+'forms/formmail_%s_thx.html' % key,PANEO_SITE_DATA_DIR+'forms/formmail_%s_thx.html' % key2)
    if os.path.exists(PANEO_SITE_DATA_DIR+'forms/formmail_%s_msg.html' % key):
        os.rename(PANEO_SITE_DATA_DIR+'forms/formmail_%s_msg.html' % key,PANEO_SITE_DATA_DIR+'orms/formmail_%s_msg.html' % key2)
    return

class List:

    def __init__(self):
        self.cms = 'formmail'
        web.header("Content-Type", "text/html; charset=UTF-8")
        web.header("Cache-Control", "no-cache, must-revalidate")
        web.header("Pragma", "no-cache")

    def GET( self ):

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        formmail = dic.get('formmail')

        if formmail is None:
            formmail = {}
            f = {'name':u'フォーム名','pageid':'index','formcss':'True','account':'gmail account','password':'gmail password','subject':u'メール件名','mailfrom':u'送信者アドレス'}
            formmail['default'] = f
            dic['formmail'] = formmail
            #TEMPLATE COPY
            formtempcopy( 'default' )

        dic.close()

        return render.formmail(  
                                  cms = self.cms,                        
                                  scfg = scfg, 
                                  mode = 'list',
                                  key = None,
                                  formmail = formmail,
                                  f = None,
                                  html_file = None,
        )


class New:

    def __init__(self):
        self.cms = 'formmail'
        web.header("Content-Type", "text/html; charset=UTF-8")
        web.header("Cache-Control", "no-cache, must-revalidate")
        web.header("Pragma", "no-cache")


    def GET( self ):

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        formmail = dic.get('formmail')
        dic.close()

        formmail = {'key':'','name':''}

        return render.formmail(
                                  cms = self.cms,                        
                                  scfg = scfg, 
                                  mode = 'new',
                                  key = None, 
                                  formmail = formmail,
                                  html_file = None,
        )


    def POST( self ):
        i = web.input()

        key = i.KEY
        #値のチェック
        web.ctx.MSG = u""

        if key == '' :
            web.ctx.MSG = u"FORM KEYを指定してください"

        if key == 'default':
            web.ctx.MSG = u"defaultは指定できません"

        reg = re.compile(r'^[0-9A-Za-z]+$')
        r = reg.search(key.encode('utf8')) 
        if r is None:
            web.ctx.MSG = u"ファイル名は半角英数字のみ有効です"

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        formmail = dic.get('formmail')

        if formmail.has_key(key):
            web.ctx.MSG = u"%sはすでに利用されています" % key 


        if web.ctx.MSG != "":
            dic.close()
            formmail = {'key':key,'name':i.NAME}
            return render.formmail(   web = web,
                                      cms = self.cms,                        
                                      scfg = scfg, 
                                      mode = 'new',
                                      key = None, 
                                      formmail = formmail,
                                      html_file = None,
            )
        else:

            f = {'name':i.NAME,'pageid':'index','formcss':'True','account':'gmail account','password':'gmail password','subject':u'メール件名','mailfrom':u'送信者アドレス'}
            formmail[key] = f
            dic['formmail'] = formmail
            #TEMPLATE COPY
            formtempcopy( key )

            dic.close()
            return web.seeother('http://' + web.ctx.host + '/paneo/formmail/form/%s/' % key)



class View:

    def __init__(self):
        self.cms = 'formmail'
        web.header("Content-Type", "text/html; charset=UTF-8")
        web.header("Cache-Control", "no-cache, must-revalidate")
        web.header("Pragma", "no-cache")

    def GET( self , key = 'default'):

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        formmail = dic.get('formmail')
        dic.close()

        if not formmail.has_key( key ) :
            return web.seeother('/paneo/formmail/')

            
        form_img = {} 
        for ii in range(1,11):
            file = 'form_%s_img%s_file' % ( key , ii )
            if IMG_CONV :
                src = "/img/form_%s_img%s" % ( key , ii )
            else:
                src = "/%s/img/form_%s_img%s" % ( PANEO_SITE_DIR , key , ii )
            form_img[file] = [ os.path.exists(PANEO_SITE_DATA_DIR + "img/form_%s_img%s" % (key,ii)) , src ]


        return render.formmail(  
                                  cms = self.cms,                        
                                  scfg = scfg, 
                                  mode = 'view',
                                  key = key,
                                  formmail = formmail,
                                  html_file = None,
                                  form_img = form_img,
        )

    def POST( self , key = 'default'):
        i = web.input(FORMCSS=False)

        dic = sqlite3dbm.sshelve.open(PANEO_DB)

        formmail = dic.get('formmail')

        if formmail is None:
            formmail = {}

        f = {}
        if formmail.has_key(key):
            f = formmail.get(key)

        #KEY変更
        if key != i.KEY and i.has_key("FORMMAIL_KEYCHANGE"):
            if formmail.has_key(i.KEY):
                web.ctx.MSG = u"%sはすでに利用されています" % i.KEY 
                return self.GET(key)
            reg = re.compile(r'^[0-9A-Za-z]+$')
            r = reg.search(i.KEY.encode('utf8')) 
            if r is None:
                web.ctx.MSG = u"FORM KEY は半角英数字のみ有効です"
                return self.GET(key)

            del formmail[key] 
            formmail[i.KEY] = f
            dic['formmail'] = formmail 
            f = formmail.get(i.KEY)
            formtempmove( key , i.KEY )

            for ii in range(1,11):
                if os.path.exists(PANEO_SITE_DATA_DIR + "img/form_%s_img%s" % (key,ii)):
                    os.rename(PANEO_SITE_DATA_DIR + "img/form_%s_img%s" % (key,ii),PANEO_SITE_DATA_DIR + "img/form_%s_img%s" % (i.KEY,ii))

            web.ctx.MSG = u"KEYが変更されました"

            return web.seeother('http://' + web.ctx.host + '/paneo/formmail/')


        #FORM削除
        if i.has_key("FORMMAIL_DELETE") :
            del formmail[key] 
            formtempdel( key )
            dic['formmail'] = formmail 
            dic.close()
            return web.seeother('http://' + web.ctx.host + '/paneo/formmail/')

        f['name'] = i.NAME
        f['pageid'] = i.PAGEID
        f['formcss'] = i.FORMCSS
        f['account'] = i.ACCOUNT
        f['password'] = i.PASSWORD
        f['subject'] = i.SUBJECT
        f['mailfrom'] = i.MAILFROM

        #画像
        img_alt = {}
        for ii in range(1,11):
            if i.has_key('form_%s_img%s_file_del' % (key,ii)):
                if os.path.exists(PANEO_SITE_DATA_DIR + "img/form_%s_img%s" % (key,ii)):
                    os.remove(PANEO_SITE_DATA_DIR + "img/form_%s_img%s" % (key,ii))
            
            fn = 'form_%s_img%s_file' % ( key , ii )
            if i.has_key(fn):
                if i[fn] != "":
                    fout = open(PANEO_SITE_DATA_DIR + "img/form_%s_img%s" % (key,ii),'wb') # creates the file where the uploaded file should be stored
                    fout.write(i[fn]) # writes the uploaded file to the newly created file.
                    fout.close() # closes the file, upload complete.

            alt = 'form_%s_img%s_alt' % (key,ii)
            img_alt[alt] = i[alt]

        f['IMG'] = img_alt

        formmail[key] = f
        dic['formmail'] = formmail 
        dic.close()



        return self.GET(key)

class Edit:

    def __init__(self):
        self.cms = 'formmail'
        web.header("Content-Type", "text/html; charset=UTF-8")
        web.header("Cache-Control", "no-cache, must-revalidate")
        web.header("Pragma", "no-cache")

    def GET( self, key='default', type = 'ent' ):

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        formmail = dic.get('formmail')
        dic.close()
        
        try:
            file = codecs.open(PANEO_SITE_DATA_DIR+'forms/formmail_' + key + '_' + type + '.html',"r","utf8")
            html_file=file.read()
            file.close()
        except:
            shutil.copyfile(PANEO_ROOT+'/_paneo_files/html/formmail_' + type + '.html', PANEO_SITE_DATA_DIR+'forms/formmail_' + key + '_' + type + '.html')
            file = codecs.open(PANEO_SITE_DATA_DIR+'forms/formmail_' + key + '_' + type + '.html',"r","utf8")
            html_file=file.read()
            file.close()

        typename = ''
        if type == 'ent':
            typename = u'入力フォーム'
        elif type == 'chk':
            typename = u'確認フォーム'
        elif type == 'thx': 
            typename = u'完了フォーム'
        elif type == 'msg':
            typename = u'メール文面'

        return render.formmail(     
                                    cms = self.cms,                        
                                    scfg = scfg, 
                                    mode = 'edit',
                                    key = key,
                                    formmail = formmail,
                                    html_file = html_file,
                                    typename = typename
        )

    def POST( self, key='default', type = 'ent' ):

        i = web.input()

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        dic.close()

        #TEMPLATEのバックアップ
        tmp = 'forms/formmail_' + key + '_' + type + '.html'
        if os.path.exists(PANEO_SITE_DATA_DIR + tmp):
            shutil.copyfile(PANEO_SITE_DATA_DIR + tmp,PANEO_SITE_DATA_DIR+PANEO_FOLDER_PREFIX+'templates/_backup/'+tmp+'.'+dt+'.bak')

        file = codecs.open(PANEO_SITE_DATA_DIR+tmp,"w","utf8")
        file.write(i.HTMLTEMPLATE)
        file.close()

        return self.GET( key,type )


